﻿using GWB.Application.System.TenantManage.Dtos;
using GWB.Core;
using GWB.Supplier;
using System.Threading.Tasks;
using Furion.DependencyInjection;
using Mapster;
using SqlSugar;
using GWB.Core.TableEntity;
using GWB.Application.System.UserManage.UserService;
using GWB.Core.Common.Entity;
using System.Collections.Generic;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using GWB.Application.System.MenuManage.MenuService;
using System.Linq;
using GWB.Core.Enum;

namespace GWB.Application.System.TenantManage.TenantService
{
    /// <summary>
    /// 租户
    /// </summary>
    public class TenantService : SqlSugarDb, ITransient, ITenantService
    {
        private readonly IUserService _userService;
        private readonly IMenuService _menuService;


        /// <summary>
        /// 
        /// </summary>
        /// <param name="userService"></param>
        public TenantService(IUserService userService, IMenuService menuService)
        {
            _userService = userService;
            _menuService = menuService;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<Result<TenantOutDto>> Add(TenantCreateOrUpdateInputDto inputDto)
        {
            var result = new Result<TenantOutDto>() { IsSuccess = true };

            using (var tran = SqlSugarDb.Db.UseTran())
            {
                //查询租户账号是否存在重复
                var tenant = await Db.Queryable<Core.TableEntity.Tenant>().Where(x => x.Account == inputDto.Account).FirstAsync();
                if (tenant != null)
                {
                    result.Msg = "账号重复";
                    result.IsSuccess = false;
                    return result;
                }
                var data = await TenantDal.Create(inputDto.Adapt<Core.TableEntity.Tenant>());
                result.Data = data.Adapt<TenantOutDto>();
                CurrentUser.AddTenantId = data.Id;
                //添加登录账号
                var user = await _userService.Add(new UserManage.Dtos.UserCreateOrUpdateInputDto()
                {
                    Account = inputDto.Account,
                    Name = inputDto.Name,
                    Phone = inputDto.Phone,
                    State= StateType.Enable
                });
                if (!user.IsSuccess)
                {
                    result.Msg = user.Msg;
                    result.IsSuccess = false;
                    tran.RollbackTran();
                    return result;
                }
                tran.CommitTran();//这个提交不能漏掉
            }
            return result;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public Task<bool> Delete(List<long> ids)
        {
            return TenantDal.Delete(ids);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<PageResult<TenantOutDto>> Page(TenantPageInputDto inputDto)
        {
            RefAsync<int> total = 0;
            var data = await SqlSugarDb.Db.Queryable<Core.TableEntity.Tenant>()
               .OrderBy(x => x.CreateAt, OrderByType.Desc)
               .Select(x => new TenantOutDto() { Id = x.Id.SelectAll() })
               .ToPageListAsync(inputDto.Current, inputDto.PageSize, total);
            return new PageResult<TenantOutDto>()
            {
                Data = data,
                Total = total,
            };
        }


        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> Update(TenantCreateOrUpdateInputDto inputDto)
        {
            return await TenantDal.Update(inputDto.Adapt<Core.TableEntity.Tenant>());
        }

        /// <summary>
        /// 编辑租户菜单
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> EditTenantMenu(TenantMenuEditInputDto inputDto)
        {

            //添加菜单

            //添加按钮


           return await _menuService.EditAssignMenu(new MenuManage.Dtos.OwnerMenuEditInputDto()
            {
               OwnerId = inputDto.TenantId,
                MenuIds=inputDto.MenuIds,
                Type=1
            });


        }

        /// <summary>
        /// 获取租户的菜单
        /// </summary>
        /// <param name="tenantId"></param>
        /// <returns></returns>
        public async Task<List<TenantMenuOutDto>> GetTenantMenus(long tenantId)
        {
          var data=await Db.Queryable<OwnerMenu,Menu>((a,b)=>new JoinQueryInfos(
              JoinType.Left,a.MenuId==b.Id ))
              .Where((a, b) =>a.OwnerId == tenantId&&a.Type==1)
              .Select((a, b) => new TenantMenuOutDto() { Id =b.Id.SelectAll() })
              .ToListAsync();
          return data;
        }
    }
}
